package db

import (
	"com.jiaguyu/model"

	"com.jiaguyu/logger"
)

func CreateFavoriteDir(favoriteDir *model.FavoriteDir) (err error) {
	tx, err := DB.Beginx()
	if err != nil {
		logger.Error("插入事务失败err%V", err)
		return
	}

	//查询名字是否存在
	var dirCount int64
	sqlStr := `select count(dir_id) from favorite_dir where user_id=? and dir_name=?`

	err = tx.Get(&dirCount, sqlStr, favoriteDir.UserId, favoriteDir.DirName)

	if err != nil {
		logger.Error("查询用户收藏表明失败%V", err)
		return
	}
	if dirCount > 0 {
		tx.Rollback()
		err = ErrNameExist
		return
	}

	sqlStr = `insert into favorite_dir(user_id,dir_id,dir_name)values(?,?,?)`
	_, err = tx.Exec(sqlStr, favoriteDir.UserId, favoriteDir.DirId, favoriteDir.DirName)
	if err != nil {
		tx.Rollback()
		err = ErrInsertFail
		return
	}

	err = tx.Commit()
	if err != nil {
		tx.Rollback()
		logger.Error("执行事务失败%V", err)
		return
	}

	logger.Error("通过%V", err)
	return
}
